import type { UploadFile } from 'element-plus';

import type { VbenFormSchema } from '#/adapter/form';
import type { OnActionClickFn, VxeTableGridOptions } from '#/adapter/vxe-table';
import type { UserApi } from '#/api/system/user';

import { h } from 'vue';

import { useAccess } from '@vben/access';
import { useAppConfig } from '@vben/hooks';
import { Plus } from '@vben/icons';

import { ElIcon } from 'element-plus';

import { z } from '#/adapter/form';
import { getCompanyList } from '#/api/system/company';
import { getDepartmentList } from '#/api/system/department';

const { hasAccessByCodes } = useAccess();
const { apiURL } = useAppConfig(import.meta.env, import.meta.env.PROD);

/** 用户表单Schema */
export function useUserFormSchema(isEdit: boolean = false): VbenFormSchema[] {
  return [
    {
      fieldName: 'id',
      component: 'Input',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'userName',
      label: '用户名',
      component: 'Input',
      componentProps: {
        placeholder: '请输入用户名',
      },
      rules: 'required',
    },
    {
      component: 'Upload',
      fieldName: 'userIcon',
      label: '用户头像',
      componentProps: {
        accept: 'image/*',
        action: `${apiURL}/upload`,
        limit: 1,
        name: 'file',
        showUploadList: false,
        listType: 'picture-card',
        onSuccess: (response: any, file: UploadFile) => {
          // 处理上传成功的响应
          if (
            response &&
            response.code === 0 &&
            response.data &&
            response.data.length > 0
          ) {
            const uploadedFile = response.data[0];
            // 更新文件对象的 URL，确保表单能获取到正确的服务器返回的 URL
            file.url = uploadedFile.url;
            // 重要：将服务器返回的 URL 存储到 response.url 中，这样表单提交时会优先使用 response.url
            file.response = {
              ...response,
              url: uploadedFile.url,
            };
          }
        },
      },
      renderComponentContent: () => {
        return {
          default: () => h(ElIcon, {}, () => [h(Plus, {}, '')]),
        };
      },
      rules: 'required',
    },
    {
      fieldName: 'password',
      label: isEdit ? '密码（留空则不修改）' : '密码',
      component: 'Input',
      componentProps: {
        placeholder: isEdit ? '留空则不修改密码' : '请输入密码',
        type: 'password',
        showPassword: true,
      },
      rules: isEdit ? '' : 'required',
    },
    {
      fieldName: 'companyId',
      label: '所属公司',
      component: 'ApiSelect',
      componentProps: {
        placeholder: '请选择所属公司',
        allowClear: false,
        api: getCompanyList,
        params: { pageNum: 1, pageSize: 999 },
        resultField: 'list',
        labelField: 'name',
        valueField: 'id',
      },
      rules: 'required',
    },
    {
      fieldName: 'departmentId',
      label: '所属部门',
      component: 'Select',
      componentProps: {
        placeholder: '请先选择公司',
        allowClear: false,
        options: [],
        // disabled: true,
        labelField: 'name',
        valueField: 'id',
      },
      dependencies: {
        triggerFields: ['companyId'],
        trigger: async (_values, formApi) => {
          // 当公司改变时，清空部门选择
          await formApi.setFieldValue('departmentId', undefined, false);
        },
        componentProps: async (values) => {
          if (values.companyId && values.companyId > 0) {
            try {
              // 调用API获取部门列表
              const result = await getDepartmentList({
                pageNum: 1,
                pageSize: 999,
                companyId: values.companyId,
              });
              const list = result.list || [];
              return {
                placeholder: '请选择所属部门',
                allowClear: false,
                options: list.map((item: any) => ({
                  label: item.name,
                  value: item.id,
                })),
                disabled: false,
              };
            } catch (error) {
              console.error('加载部门列表失败:', error);
              return {
                placeholder: '加载部门失败',
                allowClear: false,
                options: [],
                disabled: true,
              };
            }
          } else {
            return {
              placeholder: '请先选择公司',
              allowClear: false,
              options: [],
              disabled: true,
            };
          }
        },
      },
      rules: 'required',
    },
    {
      fieldName: 'realName',
      label: '真实姓名',
      component: 'Input',
      componentProps: {
        placeholder: '请输入真实姓名',
      },
    },
    {
      fieldName: 'mobile',
      label: '手机号码',
      component: 'Input',
      componentProps: {
        placeholder: '请输入手机号码',
      },
    },
    {
      fieldName: 'email',
      label: '邮箱',
      component: 'Input',
      componentProps: {
        placeholder: '请输入邮箱',
      },
    },
    {
      fieldName: 'status',
      label: '状态',
      component: 'RadioGroup',
      componentProps: {
        options: [
          { label: '启用', value: 1 },
          { label: '禁用', value: 2 },
        ],
        buttonStyle: 'solid',
        optionType: 'button',
      },
      rules: z.number().default(1),
    },
  ];
}

/** 列表搜索表单Schema */
export function useGridFormSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'userName',
      label: '用户名',
      component: 'Input',
      componentProps: {
        placeholder: '请输入用户名',
      },
    },
    {
      fieldName: 'companyId',
      label: '所属公司',
      component: 'Select',
      componentProps: {
        placeholder: '请选择公司',
        allowClear: true,
        options: [],
        api: getCompanyList,
        apiParams: { pageNum: 1, pageSize: 999 },
        labelField: 'name',
        valueField: 'id',
      },
    },
    {
      fieldName: 'departmentId',
      label: '所属部门',
      component: 'Select',
      componentProps: {
        placeholder: '请先选择公司',
        allowClear: true,
        options: [],
        labelField: 'name',
        valueField: 'id',
        // disabled: true,
      },
      dependencies: {
        triggerFields: ['companyId'],
        trigger: async (_values, formApi) => {
          // 当公司改变时，清空部门选择
          await formApi.setFieldValue('departmentId', undefined, false);
        },
        componentProps: async (values) => {
          if (values.companyId && values.companyId > 0) {
            try {
              // 调用API获取部门列表
              const result = await getDepartmentList({
                pageNum: 1,
                pageSize: 999,
                companyId: values.companyId,
              });
              const list = result.list || [];
              return {
                placeholder: '请选择部门',
                allowClear: true,
                options: list.map((item: any) => ({
                  label: item.name,
                  value: item.id,
                })),
                disabled: false,
              };
            } catch (error) {
              console.error('搜索表单：加载部门列表失败:', error);
              return {
                placeholder: '加载部门失败',
                allowClear: true,
                options: [],
                disabled: true,
              };
            }
          } else {
            return {
              placeholder: '请先选择公司',
              allowClear: true,
              options: [],
              disabled: true,
            };
          }
        },
      },
    },
    {
      fieldName: 'status',
      label: '状态',
      component: 'Select',
      componentProps: {
        placeholder: '请选择状态',
        allowClear: true,
        options: [
          { label: '启用', value: 1 },
          { label: '禁用', value: 2 },
        ],
      },
    },
  ];
}

/** 列表表格列定义 */
export function useGridColumns<T = UserApi.User>(
  onActionClick: OnActionClickFn<T>,
): VxeTableGridOptions['columns'] {
  return [
    {
      type: 'seq',
      title: '序号',
      width: 50,
    },
    {
      field: 'userName',
      title: '用户名',
      minWidth: 120,
    },
    {
      field: 'userIcon',
      title: '头像',
      minWidth: 80,
      cellRender: {
        name: 'CellImage',
        props: {
          imageKey: 'userIcon',
          size: 40,
          round: true,
          padding: '4px',
        },
      },
    },
    {
      field: 'realName',
      title: '真实姓名',
      minWidth: 100,
    },
    {
      field: 'mobile',
      title: '手机号码',
      minWidth: 120,
    },
    {
      field: 'email',
      title: '邮箱',
      minWidth: 150,
    },
    {
      field: 'companyName',
      title: '所属公司',
      minWidth: 120,
    },
    {
      field: 'departmentName',
      title: '所属部门',
      minWidth: 150,
    },
    {
      field: 'status',
      title: '状态',
      minWidth: 80,
      cellRender: {
        name: 'CellTag',
        props: {
          options: [
            { label: '启用', value: 1, color: 'success' },
            { label: '禁用', value: 2, color: 'danger' },
          ],
        },
      },
    },
    {
      field: 'lastLoginTime',
      title: '最后登录',
      minWidth: 150,
    },
    {
      field: 'editInfo',
      title: '编辑信息',
      slots: { default: 'edit-info' },
      minWidth: 200,
    },
    {
      field: 'operation',
      title: '操作',
      width: 280,
      fixed: 'right',
      align: 'center',
      cellRender: {
        attrs: {
          nameField: 'userName',
          nameTitle: '用户',
          onClick: onActionClick,
        },
        name: 'CellOperation',
        options: [
          {
            code: 'edit',
            text: '编辑',
            show: hasAccessByCodes(['system:user:edit']),
          },
          {
            code: 'bindRole',
            text: '绑定角色',
            show: hasAccessByCodes(['system:user:role']),
          },
          {
            code: 'delete',
            text: '删除',
            show: hasAccessByCodes(['system:user:delete']),
          },
        ],
      },
    },
  ];
}

/** 角色绑定表单Schema */
export function useRoleBindFormSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'userId',
      component: 'Input',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'systemId',
      label: '所属平台',
      component: 'Select',
      componentProps: {
        placeholder: '请选择平台进行筛选',
        allowClear: true,
        options: [],
      },
    },
  ];
}

/** 角色列表表格列定义 */
export function useRoleGridColumns(
  onStatusChange?: (newVal: boolean, row: any) => Promise<boolean | undefined>,
): VxeTableGridOptions['columns'] {
  const columns: VxeTableGridOptions['columns'] = [
    {
      type: 'seq',
      title: '序号',
      width: 50,
    },
    {
      field: 'title',
      title: '角色名称',
      minWidth: 150,
    },
    {
      field: 'systemName',
      title: '所属平台',
      minWidth: 120,
    },
    {
      field: 'status',
      title: '状态',
      minWidth: 80,
      cellRender: {
        name: 'CellTag',
        props: {
          options: [
            { label: '启用', value: 1, color: 'success' },
            { label: '禁用', value: 2, color: 'danger' },
          ],
        },
      },
    },
  ];

  // 如果提供了状态变更回调，添加授权管理列
  if (onStatusChange) {
    columns.push({
      field: 'isBound',
      title: '授权管理',
      minWidth: 100,
      cellRender: {
        name: 'CellSwitch',
        attrs: {
          beforeChange: async (newVal: number, row: any) => {
            const boolVal = newVal === 1;
            return await onStatusChange(boolVal, row);
          },
        },
        props: {
          activeText: '已授权',
          inactiveText: '未授权',
          activeValue: 1,
          inactiveValue: 0,
          show: hasAccessByCodes(['system:user:role:bind']),
        },
      },
    });
  }

  return columns;
}
